package com.supplychain.scm.core.oss.config;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.supplychain.scm.core.oss.AliOssService;
import com.supplychain.scm.core.oss.AliOssTemplate;
import com.supplychain.scm.core.oss.props.OssProperties;
import com.supplychain.scm.core.oss.rule.DbyOssRule;
import com.supplychain.scm.core.oss.rule.OssRule;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * oss配置类
 *
 * @author veliger
 * create on 2022-03-14
 */
@Configuration(proxyBeanMethods = false)
@AllArgsConstructor
@EnableConfigurationProperties(OssProperties.class)
@ConditionalOnProperty(value = "oss.access-key")
public class AliOssConfiguration {
	private OssProperties ossProperties;

	@Bean
	@ConditionalOnMissingBean(OssRule.class)
	public OssRule ossRule() {
		return new DbyOssRule();
	}

	@Bean
	@ConditionalOnMissingBean(AmazonS3Client.class)
	public AmazonS3 ossClient() {
		AWSCredentials credentials = new BasicAWSCredentials(ossProperties.getAccessKey(), ossProperties.getSecretKey());
		ClientConfiguration configuration = new ClientConfiguration();
		// 设置AmazonS3使用的最大连接数
		configuration.setMaxConnections(1024);
		// 设置失败请求重试次数
		configuration.setMaxErrorRetry(5);
		// 如果要用https协议，请加上下面语句
		configuration.setProtocol(Protocol.HTTPS);
		return AmazonS3ClientBuilder.standard()
				.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(ossProperties.getEndpoint(),ossProperties.getRegion()))
				.withClientConfiguration(configuration)
				.withCredentials(new AWSStaticCredentialsProvider(credentials))
				.disableChunkedEncoding().withPathStyleAccessEnabled(ossProperties.getPathStyleAccess())
				.build();
	}

	@Bean
	@ConditionalOnMissingBean(AliOssTemplate.class)
	@ConditionalOnBean({AmazonS3.class})
	public AliOssTemplate aliossTemplate(AmazonS3 amazonS3, OssRule ossRule) {
		return new AliOssTemplate(amazonS3, ossProperties, ossRule);
	}

	@Bean
	@ConditionalOnMissingBean(AliOssService.class)
	@ConditionalOnBean({AmazonS3.class})
	public AliOssService aliOssService(AliOssTemplate aliossTemplate){
		return new AliOssService(aliossTemplate);
	}
}
